"""
with cond:
    cond.wait() # 等到通知
    cond.notify() # 通知一个线程
"""
import threading
import time
# 创建一个条件变量
cond = threading.Condition()
message = None
def sender():
    global message
    with cond:
        print("发送者准备发送消息")
        time.sleep(1)
        message = "重要通知!"
        print("消息已发送")
        cond.notify()   # 通知等待的线程
def receiver():
    with cond:
        print("接收者等待消息....")
        cond.wait() # 等待通知
        print(f"收到消息:{message}")
if __name__ == '__main__':
    t_sender = threading.Thread(target=sender)
    t_receiver = threading.Thread(target=receiver)
    # 先启动接收者
    t_receiver.start()
    time.sleep(0.5)
    # 再启动发送者
    t_sender.start()
    t_sender.join()
    t_receiver.join()
    print("通信完成")
